package org.streets.wicket.event;

import org.apache.wicket.Component;
import org.apache.wicket.IClusterable;
import org.apache.wicket.Component.IVisitor;
import org.apache.wicket.ajax.AjaxRequestTarget;

/**
 * Adapted from http://talk-on-tech.blogspot.com/2008/09/wicket-loose-coupling-of-componens-for.html, written by Stefan Fussenegger.
 * @author wfaler
 *
 */
public abstract class AjaxUpdateEvent implements IClusterable {
	
	private static final long serialVersionUID = 3336598819556336810L;

	private final Component _source;
	private final AjaxRequestTarget _target;

	public AjaxUpdateEvent(final Component source,
			final AjaxRequestTarget target) {
		_source = source;
		_target = target;
	}

	public Component getSource() {
		return _source;
	}

	public AjaxRequestTarget getTarget() {
		return _target;
	}

	public final void fire() {
		getSource().getPage().visitChildren(new NotifyVisitor(this));
	}

	private static final class NotifyVisitor implements IVisitor {
		private final AjaxUpdateEvent _event;

		public NotifyVisitor(final AjaxUpdateEvent event) {
			_event = event;
		}

		public Object component(final Component component) {
			if (component instanceof IAjaxUpdateListener) {
				((IAjaxUpdateListener) component).notifyAjaxUpdate(_event);
			}
			return IVisitor.CONTINUE_TRAVERSAL;
		}
	}
}
